using System;
using System.Collections;
using System.Text.RegularExpressions;
using SecuBat.AttackPlugin;

namespace SecuBat.Analysis.Common
{
	/// <summary>
	/// Summary description for ScriptInjectionAnalysis.
	/// </summary>
	public class HtmlInjectionAnalysis : AnalysisBase, IAnalysis
	{
		private String _injectionHtml;
		private ArrayList _foundMatches;

		public string InjectionHtml
		{
			get { return _injectionHtml; }
			set { _injectionHtml = value; }
		}

		public ArrayList FoundMatches
		{
			get { return _foundMatches; }
			set { _foundMatches = value; }
		}

		public HtmlInjectionAnalysis(ICommonData data, String injectionHtml) : base(data)
		{
			InjectionHtml = injectionHtml;
			AnalysisResult = 0;
			FoundMatches = new ArrayList();
		}

		public override void DoAnalysis()
		{
			base.DoAnalysis();

			if (this.ResponseHtml != null)
			{
				if (this.ResponseHtml.Length > 0)
				{
					String searchString = InjectionHtml.Replace("\"", "\\\"");
					searchString = searchString.Replace("(", "\\(");
					searchString = searchString.Replace(")", "\\)");
					searchString = searchString.Replace("[", "\\[");
					searchString = searchString.Replace("]", "\\]");
					searchString = searchString.Replace(" ", "\\s");
					String searchExpr = String.Format("<[^>]*?>[^<]*?{0}[^>]*?<[^>]*?>", searchString);

					// Response analyzing
					Regex errorRegex = new Regex(searchExpr, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
					MatchCollection col = errorRegex.Matches(this.ResponseHtml);
					foreach (Match m in col)
					{
						FoundMatches.Add(m.Value);
						AnalysisResult += 100;
					}
				}
			}

			AnalysisText = String.Format("Number of matches found: {0}. Matches: ", this.FoundMatches.Count);
			foreach (String match in this.FoundMatches)
			{
				AnalysisText += Environment.NewLine + "\"" + match + "\"; ";
			}
		}
	}
}
